package com.sky.service.impl;


import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    //新增地址
    @Override
    public void insertAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insertAddress(addressBook);
    }

    //查询用户所有地址
    @Override
    public List<AddressBook> allAddress() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressList = addressBookMapper.allAddress(userId);
        return addressList;
    }

    //查询用户默认地址
    @Override
    public AddressBook defaultAddress() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.defaultAddress(userId);
        return addressBook;
    }

    //修改地址
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }

    //根据id删除地址
    @Override
    public void deleteAddress(Long id) {
        addressBookMapper.deleteAddress(id);
    }

    //根据id查询地址
    @Override
    public AddressBook addressById(Long id) {
        AddressBook addressBook = addressBookMapper.addressById(id);
        return addressBook;
    }

    //设置默认地址
    @Override
    @Transactional
    public void setDefaultAddress(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        AddressBook defaultAddress = addressBookMapper.defaultAddress(userId);
        if (defaultAddress!=null){
            defaultAddress.setIsDefault(0);
            addressBookMapper.setDefaultAddress(defaultAddress);
            addressBook.setIsDefault(1);
            addressBookMapper.setDefaultAddress(addressBook);
        }
        else {
            addressBook.setIsDefault(1);
            addressBookMapper.setDefaultAddress(addressBook);
        }
    }
}
